package com.xtkj.superclub_zuul.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xtkj.commons.TokenUtil;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lizheqi
 * @create 2019-12-23-15:08
 */
public class SomeFilter extends ZuulFilter{
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if(request.getRequestURI().contains("/user/register")||request.getRequestURI().contains("/user/login")){
            System.out.println(request.getRequestURI());
            return false;
        }
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //拿到请求头所带的token
        String token = request.getHeader("token");
        System.out.println(token);
        System.out.println(TokenUtil.verify(token));
        if(token==null){
            ctx.setResponseStatusCode(401);
            ctx.setSendZuulResponse(false);
            return null;
        }
        if(token!=null&&TokenUtil.verify(token)){
            //将token加入到请求头
            ctx.addZuulRequestHeader("token",token);
            return null;
        }
        //非法访问
        ctx.setResponseStatusCode(402);
        ctx.setSendZuulResponse(false);
        return null;
    }
}
